package com.sunshine.student_register.ui.activity.login;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.sunshine.student_register.R;
import com.sunshine.student_register.ui.activity.main.MainActivity;
import com.sunshine.student_register.ui.activity.register.UserRegisterActivity;

/**
 * 登录活动
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private LoginViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        getSupportActionBar().setTitle("登录学生签到系统");

        Button register = findViewById(R.id.register);
        Button login = findViewById(R.id.login);
        register.setOnClickListener(this);
        login.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.register:
                startActivity(new Intent(this, UserRegisterActivity.class));
                finish();
                break;
            case R.id.login:
                TextInputLayout tilUser = findViewById(R.id.til_user);
                TextInputEditText editUser = findViewById(R.id.edit_user);
                TextInputLayout tilPassword = findViewById(R.id.til_password);
                TextInputEditText editPassword = findViewById(R.id.edit_password);
                if (null == editUser.getText() || 0 == editUser.getText().toString().length()){
                    tilUser.setError("请输入正确的用户名");
                }else if (null == editPassword.getText() || 0 == editPassword.getText().toString().length()){
                    tilUser.setErrorEnabled(false);
                    tilPassword.setError("请输入正确的密码");
                }else {
                    tilUser.setErrorEnabled(false);
                    tilPassword.setErrorEnabled(false);

                    if (viewModel.hasLogin(editUser.getText().toString(), editPassword.getText().toString())){
                        viewModel.setLoginUser();
                        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(this, MainActivity.class));
                        finish();
                    }else {
                        Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }
}
